// 1. 引入当前项目所需的所有包
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
require('./database/connect.js')  //连接数据库
const { checkToken } = require('./utils/tools.js');
var cors = require('cors')
require('./socket/socketServer.js')

// 2. 引入项目路由文件（不同路由文件为客户端提供不同的接口服务）
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var fanjiRouter = require('./routes/fanji.js');
var RoleRouter = require('./routes/role.js');


// 3. 创建服务对象
var app = express();
app.use(cors())   //开放跨域访问

// 服务端代理配置
const { createProxyMiddleware } = require('http-proxy-middleware');
const apiProxy = createProxyMiddleware({
  target: 'https://www.zhipin.com',
  changeOrigin: true,
  pathRewrite: {'^/proxy' : ''},
  on: {
    proxyReq: (proxyReq, req, res) => { //自定义代理请求头相关配置 【请求伪装】
      /* handle proxyReq */
      proxyReq.setHeader('referer', 'https://www.zhipin.com/web/geek/job?');
      proxyReq.setHeader('user-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0');
      proxyReq.setHeader('cookie',`lastCity=101040100; ab_guid=53ed1ecd-daa6-49c3-91f3-fed7ffa766f5; __zp_seo_uuid__=c2f4e00f-9809-4cc2-bb7d-b1cbeb6a3b13; __l=r=https%3A%2F%2Fwww.bing.com%2F&l=%2Fgongsi%2Ffa2f92669c66eee31Hc%7E.html&s=1; Hm_lvt_194df3105ad7148dcf2b98a91b5e727a=1739265560,1739410959; HMACCOUNT=9D879E1C29E5DDB1; __g=-; Hm_lpvt_194df3105ad7148dcf2b98a91b5e727a=1739410967; __c=1739410964; __a=60513999.1728618368.1739265559.1739410964.9.3.3.9; __zp_stoken__=e736fwrPCqxNAXBYRFRJbYAtVfGJ9ZcK6w4dow4hdc8KCwrdjV2XCt3LCmWXDh8KqWMOIwqlQwo9PwolzwpJJxIjCqcKZw4DCl0%2FCoMK5wpzEnsOyw57CmMKPw6rDg8KkOTYMEwsQCw4VDQoNEQoNCg0WDRUSFRMMFBcUPy%2FDu8KSLj1FQkApU0xUDlVkXkthSQpoTE07QBcWZhZAKTtAOzzCumTCuwvDgVzDgBDDgmPDiFtAQzxDwr4uMCrDhksMZBDDhjQMwrvDgRfCu8OhYMOMXMKKbsK5wrzDlDc6PcK8xYRCORlCRj5HPj07PjkpPRjDi2fCimrDgcK%2BGi48JkY5PkZIPjk%2BSEZELT5FFyw5Oyw6FgwTERgtRsK%2FwqzDg8OmOT4%3D`)
    },
    proxyRes: (proxyRes, req, res) => {
      /* handle proxyRes */
    }
  }, 
});
app.use('/proxy',apiProxy)


// 4. 为服务对象配置中间件（提供特有能力，如：USB转接头）

app.use(logger('dev'));
app.use(express.json({limit:'500mb'}));  //这个中间件，可以协助服务端处理客户端提交的json数据
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public'))); //这个中间件，是为了引导客户端顺利找到服务端的静态资源（img、html、css文件）

// 5. 将路由接口模块集成到app应用对象中
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/fanji',(req,res,next)=>{
  checkToken(req,res,next) //访问fanjiRouter前做token认证
},fanjiRouter)
app.use('/role',(req,res,next)=>{
  checkToken(req,res,next) 
},RoleRouter)

// 6. 对外抛出app服务对象
module.exports = app;
